<?php

namespace app\admin\controller\hospital;

use app\common\controller\Backend;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class GeneralTimes extends Backend
{

    /**
     * GeneralTimes模型对象
     * @var \app\common\model\hospital\GeneralTimes
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\hospital\GeneralTimes;
        $this->view->assign("weekdaysList", $this->model->getWeekdaysList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $params =$this->request->param('');
            $list = $this->model

                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','week_name','week_days','time_text','createtime','updatetime']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        $mids = $this->model->column('week_days');
        foreach ($mids as $k=>$v){
            $v = explode(',',$v);
            if(count(array_intersect($v,$params['week_days']))>0){
                $this->error('日期重复');
            }
        }
        $weeksinfoList=$this->model->weeksinfoList;

        $weeks =$params['week_days'];

        $arr=[];
        foreach ($weeks as $k=>$v){
            $arr[]=$weeksinfoList[intval($v)-1];
        }
        $params['week_days'] =implode(',',$params['week_days']);
        $params['week_name']=implode(',',$arr);

        if(isset($params['job'])){
            if(empty($params['job'])){
                $this->error('详情页预约时间段不能为空');
            }else{
                $i=0;
                $job=[];
                foreach($params['job'] as $k=>$v){
                    if(!$v['startime']){
                        $this->error('第'.($i+1).'个预约开始时间不能为空');
                    }
                    if(!$v['endtime']){
                        $this->error('第'.($i+1).'个预约结束时间不可为空');
                    }
                    if($v['endtime']<=$v['startime']){
                        $this->error('第'.($i+1).'个结束时间应大于开始时间');
                    }
                    if(!in_array($v['startime'],$job)){
                        $job[]=$v['startime'];
                    }else{
                        $this->error('预约时间段重复');
                    }
                    $i++;
                }
            }

        }else{
            $this->error('详情页预约时间段不能为空');
        }
        if(isset($params['resume'])){
            if(empty($params['resume'])){
                $this->error('具体预约时间段不能为空');
            }else{
                $i=0;
                $resume=[];
                foreach($params['resume'] as $k=>$v){
                    if(!$v['startime']){
                        $this->error('第'.($i+1).'个预约开始时间不能为空');
                    }
                    if(!$v['endtime']){
                        $this->error('第'.($i+1).'个预约结束时间不可为空');
                    }
                    if($v['endtime']<=$v['startime']){
                        $this->error('第'.($i+1).'个结束时间应大于开始时间');
                    }
                    if(!in_array($v['startime'],$resume)){
                        $resume[]=$v['startime'];
                    }else{
                        $this->error('预约时间段');
                    }
                    $i++;
                }
            }

        }else{
            $this->error('具体预约时间段不能为空');
        }

        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            //添加
            if(isset($params['job'])){
                \app\common\model\hospital\GeneralTime::addlivejobs($params['job'],$this->model->id,0,$params['week_name'],$params['week_days']);
            }
            //添加
            if(isset($params['resume'])){
                \app\common\model\hospital\GeneralAppoint::addlivejobs($params['resume'],$this->model->id,0,$params['week_name'],$params['week_days']);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        $row['week_days'] =explode(',',$row['week_days']);

        $jobs = \app\common\model\hospital\GeneralTime::where(['time_id'=>$ids])
            ->order('createtime desc')->select();
        $resumes = \app\common\model\hospital\GeneralAppoint::where(['time_id'=>$ids])

            ->where(['week_days'=>$row['week_days'][0]])
            ->order('createtime desc')
            ->select();
        $this->assignconfig('jobs', $jobs);
        $this->assignconfig('resumes', $resumes);
        $this->view->assign('jobs', $jobs);
        $this->view->assign('totaljobs', count($jobs));
        $this->view->assign('resumes', $resumes);
        $this->view->assign('totalresumes', count($resumes));
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        $mids = $this->model->where('id','<>',$ids)->column('week_days');
        foreach ($mids as $k=>$v){
            $v = explode(',',$v);
            if(count(array_intersect($v,$params['week_days']))>0){
                $this->error('日期重复');
            }
        }
        $weeksinfoList=$this->model->weeksinfoList;

        $weeks =$params['week_days'];

        $arr=[];
        foreach ($weeks as $k=>$v){
            $arr[]=$weeksinfoList[intval($v)-1];
        }
        $params['week_days'] =implode(',',$params['week_days']);
        $params['week_name']=implode(',',$arr);
        if (isset($params['job'])) {
            if (empty($params['job'])) {
                $this->error('详情页预约时间段不能为空');
            } else {
                $i = 0;
                $job = [];
                foreach ($params['job'] as $k => $v) {
                    if (!$v['startime']) {
                        $this->error('第' . ($i + 1) . '个预约开始时间不能为空');
                    }
                    if (!$v['endtime']) {
                        $this->error('第' . ($i + 1) . '个预约结束时间不可为空');
                    }
                    if ($v['endtime'] <= $v['startime']) {
                        $this->error('第' . ($i + 1) . '个结束时间应大于开始时间');
                    }
                    if (!in_array($v['startime'], $job)) {
                        $job[] = $v['startime'];
                    } else {
                        $this->error('预约时间段重复');
                    }
                    $i++;
                }
            }

        } else {
            $this->error('详情页预约时间段不能为空');
        }
        if (isset($params['resume'])) {
            if (empty($params['resume'])) {
                $this->error('具体预约时间段不能为空');
            } else {
                $i = 0;
                $resume = [];
                foreach ($params['resume'] as $k => $v) {
                    if (!$v['startime']) {
                        $this->error('第' . ($i + 1) . '个预约开始时间不能为空');
                    }
                    if (!$v['endtime']) {
                        $this->error('第' . ($i + 1) . '个预约结束时间不可为空');
                    }
                    if ($v['endtime'] <= $v['startime']) {
                        $this->error('第' . ($i + 1) . '个结束时间应大于开始时间');
                    }
                    if (!in_array($v['startime'], $resume)) {
                        $resume[] = $v['startime'];
                    } else {
                        $this->error('预约时间段');
                    }
                    $i++;
                }
            }

        } else {
            $this->error('具体预约时间段不能为空');
        }
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $result = $row->allowField(true)->save($params);
            //添加
            if (isset($params['job'])) {
                \app\common\model\hospital\GeneralTime::addlivejobs($params['job'], $ids, 0, $params['week_name'], $params['week_days']);
            }
            //添加
            if (isset($params['resume'])) {
                \app\common\model\hospital\GeneralAppoint::addlivejobs($params['resume'], $ids, 0, $params['week_name'], $params['week_days']);
            }
            Db::commit();
        } catch (ValidateException | PDOException | \Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function savesAppoint($id)
    {
     $current =time();
    $h= \app\common\model\Hospital::where(['id'=>$id])->find();
    if(empty($h['weigh'])){
        $h->data(['weigh'=>$id]);
        $h->save();
    }
     $times =$this->model->select();
     Db::startTrans();
     foreach ($times as $k=>$v){
         $saves=['hospital_id'=>$id,
             'week_name'=>$v['week_name'],
             'week_days'=>$v['week_days'],
             'time_text'=>$v['time_text'],
             'createtime'=>$current,
             'updatetime'=>$current
         ];
         $time_id = (new  \app\common\model\Hospitaltime())->insertGetId($saves);
         $time=(new \app\common\model\hospital\GeneralTime())->where(['time_id'=>$v['id']])->select();
         $save_times=[];
         foreach ($time as $k1=>$v1){
             $save_times[]=[
                 'time_id'=>$time_id,
                 'hospital_id' =>$id,
                 'endtime'=>$v1['endtime'],
                 'startime'=>$v1['startime'],
                 'week_name'=>$v1['week_name'],
                 'week_days'=>$v1['week_days'],
                 'createtime' => $current];
         }
         $save_time_appoints=[];
         $appoints=(new \app\common\model\hospital\GeneralAppoint())
             ->where(['time_id'=>$v['id']])
             ->select();
         foreach ($appoints as $k2=>$v2){
             $save_time_appoints[]=[
                 'time_id'=>$time_id,
                 'hospital_id' =>$id,
                 'endtime'=>$v2['endtime'],
                 'startime'=>$v2['startime'],
                 'week_name'=>$v2['week_name'],
                 'week_days'=>$v2['week_days'],
                 'createtime' => $current];
         }
         if(count($save_times)>0){
             (new   \app\common\model\Hospitaltimes())->saveAll($save_times);
         }
         if(count($save_time_appoints)>0){
             (new  \app\common\model\Hospitalappoint())->saveAll($save_time_appoints);
         }

      }
     Db::commit();

    }
    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
               \app\common\model\hospital\GeneralAppoint::where(['time_id'=>$item['id']])->delete();
               \app\common\model\hospital\GeneralTime::where(['time_id'=>$item['id']])->delete();
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
